<?php
// 应用公共文件test
use app\beautiful\model\finance\SettleOrderModel;
use app\beautiful\model\LevelBenefitsModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\member\MemberBalanceModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\BuyOrderModel;
use app\beautiful\model\order\OrderRefundModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\setting\ConsumeBonusSettingModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\cash\model\OpenTableModel;
use app\common\model\account\ShopAccountModel;
use app\common\model\MemberMoneyDetailModel;
use app\stores\helper\payment\PaymentGoodsOrderHelper;
use app\stores\logic\LogsLogic;
use app\stores\logic\MemberWalletLogic;
use app\stores\model\member\MemberLevelModel;
use app\stores\model\member\MemberSearchModel;
use app\stores\model\order\GoodsOrderModel;
use app\beautiful\model\setting\PartnerBonusSettingModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\PartnerPromotionSettingModel;
use app\common\model\DataConfigModel;
use app\beautiful\model\member\MemberLockModel;
use app\common\model\ShopBalanceLogsModel;
use app\stores\model\promotion\PromotionmemberModel;
use app\stores\model\promotion\TeamActivityModel;
use app\stores\model\promotion\ActivityModel;
use app\stores\model\promotion\PromotionmoneydetailModel;
use app\stores\model\promotion\TeamModel;
use app\stores\model\promotion\PromotionrecordModel;
use \PhpOffice\PhpSpreadsheet\IOFactory;
function doMoveDir($source, $target) {

    if (!is_dir($target)) {
        if (!mkdir($target)) {
            return false;
        }
    }
    $d = dir($source);
    while (($entry = $d->read()) !== false) {
        if (is_dir($source . $entry)) {
            if ($entry == "." || $entry == "..") {
                continue;
            } else {
                doMoveDir($source . $entry . '/', $target . $entry . '/');
            }
        } else {
            if (!copy($source . $entry, $target . $entry)) {
                return false;
            }
        }
    }
    return true;
}

function wyuLog($file,$str){
    $file = root_path().'/public/'.$file;
    $fp = fopen($file,'a+');
    fwrite($fp, $str."\n");
    fclose($fp);
}

// 应用公共文件

function checkStoreAction($action){
    $actions=[
        'authLogin',
        'login',
        'storeLayout',
        'getContactData',
        'getConsoleData',
        'getDataStatistics'
    ];
    if(!in_array($action,$actions)){
        return false;
    }
    return true;
}

function checkAgentAction($action){
    $actions=[
        'home',
        'login',
        'storeLayout',
        'getContactData',
        'getConsoleData',
        'getDataStatistics'
    ];
    if(!in_array($action,$actions)){
        return false;
    }
    return true;
}



function checkDateFormat($date)
{
    //匹配日期格式
    if (preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
        //检测是否为日期
        if (checkdate($parts[2], $parts[3], $parts[1]))
            return true;
        else
            return false;
    } else
        return false;
}

//将一个数组的主键作为KEY
function array_by_key($data, $key = 'id')
{
    $return = [];
    foreach ($data as $val) {
        $return[$val[$key]] = $val;
    }
    return $return;
}

function get_img($img, $type = '')
{
    $img = str_replace('\\', '/', $img);
    if (empty($type))
        return $img;
    $imgs = explode('.', $img);
    $imgs[count($imgs) - 1] = $type . '.' . $imgs[count($imgs) - 1];
    return join('.', $imgs);
}


/*
 * 经度纬度 转换成距离
 * $lat1 $lng1 是 数据的经度纬度
 * $lat2,$lng2 是获取定位的经度纬度
 */
function rad($d)
{
    return $d * 3.1415926535898 / 180.0;
}

function get_distance_none($lat1, $lng1, $lat2, $lng2)
{
    $EARTH_RADIUS = 6378.138;
    $radLat1 = rad($lat1);
    //echo $radLat1;
    $radLat2 = rad($lat2);
    $a = $radLat1 - $radLat2;
    $b = rad($lng1) - rad($lng2);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 10000);
    return $s;
}

function get_distance($lat1, $lng1, $lat2=0, $lng2=0)
{
    $s = '0m';
    if($lat2>0 && $lng2>0){
        $s = get_distance_none($lat1, $lng1, $lat2, $lng2);
        $s = $s / 10000;
        if ($s < 1) {
            $s = round($s * 1000);
            $s .= 'm';
        } else {
            $s = round($s, 2);
            $s .= 'km';
        }
    }

    return $s;
}


/**
 * 根据经纬度和半径计算出范围
 * @param string $lat 纬度
 * @param String $lng 经度
 * @param float $radius 半径 m
 * @return array 范围数组
 */
function calc_scope($lat, $lng, $radius)
{
    $degree = (24901 * 1609) / 360.0;
    $dpmLat = 1 / $degree;
    $radiusLat = $dpmLat * $radius;
    $minLat = $lat - $radiusLat;       // 最小纬度
    $maxLat = $lat + $radiusLat;       // 最大纬度
    $mpdLng = $degree * cos($lat * (3.141592653 / 180));
    $dpmLng = 1 / $mpdLng;
    $radiusLng = $dpmLng * $radius;
    $minLng = $lng - $radiusLng;      // 最小经度
    $maxLng = $lng + $radiusLng;      // 最大经度
    $scope = [
        'minLat' => $minLat,
        'maxLat' => $maxLat,
        'minLng' => $minLng,
        'maxLng' => $maxLng
    ];
    return $scope;
}


/**
 * 判断输入的字符串是否是一个合法的电话号码（仅限中国大陆）
 * @param string $string
 * @return boolean
 */
function is_phone($string)
{
    if (preg_match('/^[0,4,8]\d{2,3}-\d{7,8}$/', $string))
        return true;
    return false;
}

/**
 * 验证手机号
 */
function is_mobile($string)
{
    return preg_match('/^1[3456789]\d{9}$/', $string);
}

//获取安全的JSON 或数组
function security_json_or_array($str)
{
    if (is_array($str)) {
        $datas = $str;
    } else {
        $datas = json_decode($str, true);
        if (json_last_error() != JSON_ERROR_NONE) {
            return [];
        }
    }
    if (empty($datas)) return [];
    $return = [];
    foreach ($datas as $key => $val) {
        if (is_array($val)) {
            $return[$key] = security_json_or_array($val);
        } else {
            $return[$key] = security_editor_textarea($val);
        }
    }
    return $return;
}

//获取安全的textarea
function security_editor_textarea($str)
{
    $farr = [
//        "/\s+/", //过滤多余的空白
        "/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU"
    ];
    $tarr = [
//        " ",
        "＜\\1\\2\\3＞",
        "\\1\\2",
    ];
    $str = preg_replace($farr, $tarr, $str);

    return $str;
}

//获取安全的HTML
function security_editor_html($str)
{
    $str = security_editor_textarea($str);
    $str = str_replace(["\\r\\n", "\\r", "\\n"], "", $str);
    return $str;
}

//加解密函数

function auth_code($string, $operation = 'ENCODE', $key = '', $expiry = 0)
{
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;
    // 密匙
    $key = md5($key ? $key : config('auth.code'));
    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) :
        substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
//解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)
        ) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc . str_replace('=', '', base64_encode($result));
    }
    //替换url包成url参数唯一性；
}


/*
 * @param $cardNum string 卡号
 * @param $length  int      每几个为一组
 * @param $division
 *
 */
function format_card_num($cardNum, $glue = ' ', $length = 3)
{
    return implode($glue, str_split($cardNum, $length));
}


/**
 * 判断区间
 * @param $stage_data array 范围数组 如 [99,199,299,399]
 * @param $stage_num integer 需要判断的数字
 * @return int 区间前一位 索引值
 */
function sorts($stage_data, $stage_num)
{
    array_push($stage_data, $stage_num);
    $data = array_unique($stage_data);
    sort($data);
    return array_search($stage_num, $data);
}


function is_image($imgurl)
{
    $ext1 = strtolower(substr($imgurl, strrpos($imgurl, '.')));
    $arr = ['.jpg', '.gif', '.png', '.jpeg'];
    return in_array($ext1, $arr);
}


/**
 * 将元 转换成 分
 * @param float $money 价格浮点数 元
 * @return mixed 价格的 分
 */
function money_to_int($money)
{
    return (int)bcmul($money, 100, 0);
}

/**
 * 价格格式化
 * @param int $money 价格 分
 * @param bool $format 是否格式化 默认 否
 * @return float|string  格式后的价格
 */
function wxb_money_format($money, $format = false)
{
    return $format ? number_format($money / 100, 2) : round($money / 100, 2);
}


/*
 * 线段切割法,分割砍价金额
*/
function line_cut($money, $people)
{
    //获取切割处
    $temp = [];
    while (count($temp) < $people - 1) {
        $number = mt_rand(1, $money - 1);
        $temp[$number] = 1;
    }
    //补头补尾
    $temp[0] = 1;
    $temp[$money] = 1;
    $temp = array_keys($temp);
    sort($temp);
    //循环分配
    $red_packet = [];
    for ($i = 0; $i < $people; $i++) {
        $red_packet[] = $temp[$i + 1] - $temp[$i];
    }
    $max_key = array_search(max($red_packet), $red_packet);
    if ($max_key > 0) {
        list ($red_packet[0], $red_packet[$max_key]) = [$red_packet[$max_key], $red_packet[0]];
    }
    return $red_packet;
}


function check_seven_days($date_begin, $date_end)
{
    //默认返回近七天数据、包括今天
    if ($date_begin && $date_end) {
        if ($date_begin > $date_end) {
            return false;
        }
        if (($date_end - $date_begin) / 86400 > 7) {
            return false;
        }
        $date = ['date_begin' => $date_begin, 'date_end' => $date_end];
    } else {
        $date_begin = strtotime(date("Y-m-d", time()));
        $date_end = $date_begin + 86400;
        $date = ['date_begin' => $date_begin, 'date_end' => $date_end];
    }
    return $date;
}

/**
 * 生成订单号
 */
function order_no()
{
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 判断一个坐标是否在一个多边形内（由多个坐标围成的）
 * 基本思想是利用射线法，计算射线与多边形各边的交点，如果是偶数，则点在多边形外，否则
 * 在多边形内。还会考虑一些特殊情况，如点在多边形顶点上，点在多边形边上等特殊情况。
 * @param $point array 指定点坐标
 * @param $pts array 多边形坐标 顺时针方向
 */
function is_point_in_polygon($point, $pts)
{
    $N = count($pts);
    $boundOrVertex = true; //如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
    $intersectCount = 0;
    $precision = 2e-10; //浮点类型计算时候与0比较时候的容差
    $p1 = 0;
    $p2 = 0;
    $p = $point; //测试点
    $p1 = $pts[0];
    for ($i = 1; $i <= $N; ++$i) {
        if ($p['lng'] == $p1['lng'] && $p['lat'] == $p1['lat']) {
            return $boundOrVertex;
        }

        $p2 = $pts[$i % $N];
        if ($p['lat'] < min($p1['lat'], $p2['lat']) || $p['lat'] > max($p1['lat'], $p2['lat'])) {
            $p1 = $p2;
            continue;
        }

        if ($p['lat'] > min($p1['lat'], $p2['lat']) && $p['lat'] < max($p1['lat'], $p2['lat'])) {
            if ($p['lng'] <= max($p1['lng'], $p2['lng'])) {
                if ($p1['lat'] == $p2['lat'] && $p['lng'] >= min($p1['lng'], $p2['lng'])) {
                    return $boundOrVertex;
                }
                if ($p1['lng'] == $p2['lng']) {
                    if ($p1['lng'] == $p['lng']) {
                        return $boundOrVertex;
                    } else {
                        ++$intersectCount;
                    }
                } else {
                    $xinters = ($p['lat'] - $p1['lat']) * ($p2['lng'] - $p1['lng']) / ($p2['lat'] - $p1['lat']) + $p1['lng'];//cross point of lng
                    if (abs($p['lng'] - $xinters) < $precision) {//overlies on a ray
                        return $boundOrVertex;
                    }
                    if ($p['lng'] < $xinters) {
                        ++$intersectCount;
                    }
                }
            }
        } else {
            if ($p['lat'] == $p2['lat'] && $p['lng'] <= $p2['lng']) {
                $p3 = $pts[($i + 1) % $N];
                if ($p['lat'] >= min($p1['lat'], $p3['lat']) && $p['lat'] <= max($p1['lat'], $p3['lat'])) { //p.lat lies between p1.lat & p3.lat
                    ++$intersectCount;
                } else {
                    $intersectCount += 2;
                }
            }
        }
        $p1 = $p2;
    }
    if ($intersectCount % 2 == 0) {//偶数在多边形外
        return false;
    } else { //奇数在多边形内
        return true;
    }
}

/**
 * 检测时间段 是否有交叉
 */
function compare_date($begin, $over)
{
    sort($begin);
    sort($over);
    for ($i = 1; $i < count($begin); $i++) {
        if ($begin[$i] <= $over[$i - 1]) {
            return false;
        }
    }
    return true;
}


/**
 * 根据数组过滤KEY
 * @param array $sampleArray 对比的数组
 * @param array $filterArray 要过滤的数组
 * @return array
 */
function array_filter_key($sampleArray, $filterArray): array
{
    $return = [];
    foreach ($sampleArray as $key => $value) {
        if (is_array($value)) {
            $_data = $filterArray[$key] ?? [];
            $_data = is_array($_data) ? $_data : [];
            //如果是空数组 或者是 索引数组 直接赋值
            if (count($value) == 0 || !\think\helper\Arr::isAssoc($value)) {
                $return[$key] = !\think\helper\Arr::isAssoc($_data) ? $_data : [];
            } else {
                $return[$key] = array_filter_key($value, $_data);
            }

        } else {
            if (!isset($filterArray[$key])) {
                $return[$key] = $value;
            } else {
                $return[$key] = is_array($filterArray[$key]) ? $value : $filterArray[$key];
            }
        }
    }
    return $return;
}

/**
 * 对象转数组
 * @param object $object json 的object
 * @return array
 */
function object_to_array($object): array
{
    return json_decode(json_encode($object), true);
}


/**
 * 数组转对象
 * @param array $data
 * @return object
 */
function array_to_object($data): object
{
    return json_decode(json_encode($data));
}

/**
 * 字符串排序
 * @param $str
 */
function str_sort($str)
{
    $change_after = [];
    for ($i = 0; $i < strlen($str); $i++) {
        if ($str[$i] != ' ') {
            $temp_str = ord($str[$i]);
            $change_after[$i] = $temp_str;
        }
    }
    sort($change_after);
    $rstr = '';
    for ($i = 0; $i < count($change_after); $i++) {
        $rstr .= chr($change_after[$i]);
    }
    return $rstr;
}


function rm_symbol($str)
{
    $char = " 。、！？：；﹑•＂…‘’“”〝〞∕¦‖—　〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔！¡？¿﹖﹌﹏﹋＇´ˊˋ―﹫︳︴¯＿￣﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼（）";
    $pattern = [
        "/[[:punct:]]/i", //英文标点符号
        '/[' . $char . ']/u', //中文标点符号
        '/[ ]{2,}/',
        '/\s+/',
    ];
    return preg_replace($pattern, '', $str);
}


/**
 * 获取表前缀
 */
function get_table_prefix()
{
    return config("database.connections.mysql.prefix");
}


/**
 * 去除所有空 和换行
 */
function clear_space($str)
{
    $search = [" ", "　", "\n", "\r", "\t"];
    $replace = ["", "", "", "", ""];
    return str_replace($search, $replace, $str);
}


/**
 * @param $v
 * @return mixed
 */
function json_decode_array($v)
{
    $v = htmlspecialchars_decode($v);
    $v = security_editor_html($v);
    return json_decode($v, true);
}

/**
 * 域名是否含有 协议
 * @param string $domain 检测域名
 * @return int
 */
function domain_have_agreement($domain)
{
    $domain = strtolower($domain);
    $preg = "/^http(s)?|ws(s)?|file?|ftp?:\\/\\/.+/";
    return preg_match($preg, $domain);
}

/**
 * 检查是否是合法域名
 */
function check_expire_domain($domain)
{
    $domain = "http://" . $domain;
    return (bool)filter_var($domain, FILTER_SANITIZE_URL, FILTER_FLAG_HOSTNAME);
}

function countage($birthday)
{
    if (date("n") >= date("n", strtotime($birthday))) {
        $month = date("n") - date("n", strtotime($birthday));
        $year = date("Y") - date("Y", strtotime($birthday));
    } else {
        $month = date("n") + 12 - date("n", strtotime($birthday));
        $year = date("Y") - date("Y", strtotime($birthday)) - 1;
    }
    if ($year != 0) {
        if ($month != 0) {
            return $year . "岁" . $month . "个月";
        } else {
            return $year . "岁";
        }
    } else {
        if ($month != 0) {
            return $month . "个月";
        } else {
            return "满月";
        }
    }

}

/**
 * 隐藏手机号中间四位
 * @param $str
 * @return string|string[]
 */
function yc_phone($str){
    if(is_mobile($str)){
        $str=substr_replace($str,'****',3,4);
    }
    return $str;
}

//二维数组排序
function sortArr($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
    $key_arrays =array();
    if(is_array($arrays)){
        foreach ($arrays as $array){
            if(is_array($array)){
                $key_arrays[] = $array[$sort_key];
            }else{
                return false;
            }
        }
    }else{
        return false;
    }
    array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
    return $arrays;
}


function array_unique_fb($array2D)
{
    foreach ($array2D as $v)
    {
        $v = join(",",$v);  //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[] = $v;
    }

    $temp = array_unique($temp);    //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v)
    {
        $temp[$k] = explode(",",$v);   //再将拆开的数组重新组装
    }
    return $temp;
}

function toHeavy($data,$column){
    $i = [];
    foreach($data as $key => &$value){
        if(in_array($value[$column],$i)){
            unset($data[$key]);
        }else{
            $i = $value;
        }
    }
    return $data;
}



/**
 * 替换图片
 * @param $url 使用的图片链接
 * @param null $pre_url 之前使用的图片链接 null代表第一次上传
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function imgReplaceAct($url,$pre_url=null){
    imgNoUseAct($pre_url);
    imgUseAct($url);
   return true;
}

/**
 * 数组里面图片失效
 * @param array $datas
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function arrayNoUseImg(array $datas){
    if(!is_array($datas)){
        return false;
    }

    foreach ($datas as $data){
        if(is_array($data)){
            if($data['type']=='pic'){
                imgNoUseAct($data['content']);
            }
        }else{
            imgNoUseAct($data);
        }
    }
    return true;
}

/**
 * 数组里面图片有效
 * @param array $datas
 * @return false
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function arrayUseImg(array $datas){
    if(!is_array($datas)){
        return false;
    }
    foreach ($datas as $data){
        if(is_array($data)){
            if($data['type']=='pic'){
                imgUseAct($data['content']);
            }
        }else{
            imgUseAct($data);
        }
    }
}



/**
 * 有效的链接
 * @param $url
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function imgUseAct($url){
    if(null !== $img = \app\common\model\ImgModel::where([['url','=',$url]])->find()){
        $img->is_use=1;
    }
    $img->save();
    return true;
}

/**
 * 无效的链接
 * @param null $url
 * @return bool
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\DbException
 * @throws \think\db\exception\ModelNotFoundException
 */
function imgNoUseAct($url=null){
    if($url != null){
        if(null !== $img = \app\common\model\ImgModel::where([['url','=',$url]])->find()){
            $img->is_use=0;
        }
        $img->save();
    }
    return true;
}

/**
 *求两个已知经纬度之间的距离,单位为米
 * @param $lng1 $经度
 * @param $lat1 $纬度
 * @param $lng2 $经度
 * @param $lat2 $纬度
 * @return float|int 单位 米
 */
function getDistance($lng1, $lat1, $lng2, $lat2)
{
    // 将角度转为弧度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}

/*二维数组添加数据*/
function addTwoData($data,$arr){
    array_walk($data, function (&$value, $key, $arr) {
        $value = array_merge($value, $arr);
    }, $arr);

    return $data;
}
/*生成订单号*/
function getVerifyCode($order_id=0){
    $code = time().str_pad($order_id,6,0,STR_PAD_LEFT);;
    return $code;
}

/*根据当前用户等级匹配价格(登录的用户才会有等级匹配的价格)*/
function getPrice($goods,$member,$is_two_array=0){
    if($goods && $member){
        if($is_two_array){
            foreach ($goods as $k=>$v){
                //无折扣
                $goods[$k]['price'] = $v['original_price'];
                $goods[$k]['vip_discount_price'] = null;
                if($v['vip_discount_type']>0 && $v['discount_detail']){
                    for ($i=0;$i<count($v['discount_detail']);$i++){
                        if($v['discount_detail'][$i]['level_id']==$member->level_id){
                            if($v['vip_discount_type']==1){
                                $goods[$k]['price'] = $v['original_price']*($v['discount_detail'][$i]['member_price']/10);
                                $goods[$k]['vip_discount_price'] = null;
                            }
                            if($v['vip_discount_type']==2){
                                $goods[$k]['price'] = $v['discount_detail'][$i]['bid_price'];
                                $goods[$k]['vip_discount_price'] = $v['discount_detail'][$i]['bid_price'];
                            }
                            if($v['vip_discount_type']==3){
                                $goods[$k]['price'] = $v['original_price']-$v['discount_detail'][$i]['reduce_price'];
                                $goods[$k]['vip_discount_price'] = $v['discount_detail'][$i]['reduce_price'];
                            }
                        }
                    }
                }

                unset($goods[$k]['discount_detail']);

            }
        }else{
            $goods['price'] = $goods['original_price'];
            $goods['vip_discount_price'] = null;
            if($goods['vip_discount_type']>0 && $goods['discount_detail']){
                for ($i=0;$i<count($goods['discount_detail']);$i++){
                    if($goods['discount_detail'][$i]['level_id']==$member->level_id){
                        if($goods['vip_discount_type']==1){
                            $goods['price'] = $goods['original_price']*($goods['discount_detail'][$i]['member_price']/10);
                            $goods['vip_discount_price'] = null;
                        }
                        if($goods['vip_discount_type']==2){
                            $goods['price'] = $goods['discount_detail'][$i]['bid_price'];
                            $goods['vip_discount_price'] = $goods['discount_detail'][$i]['bid_price'];
                        }
                        if($goods['vip_discount_type']==3){
                            $goods['price'] = $goods['original_price']-$goods['discount_detail'][$i]['reduce_price'];
                            $goods['vip_discount_price'] = $goods['discount_detail'][$i]['reduce_price'];
                        }
                    }
                }
            }
        }


    }
    return $goods;
}

/*sku根据当前用户等级匹配价格*/
function skuMemberPrice($vip_discount_type,$sku,$member,$shop_id,$type=2,$origin_type=1,$num=1){
    foreach ($sku as $kk=>$vv){
        $vv['vip_discount_type'] = $vip_discount_type;
        if($member){
            $vv['origin_type'] = $origin_type;
            $price = $origin_type==1?$vv['original_price']:$vv['crossed_price'];
            $return = getMemberPrice($member,$shop_id,$vv,$price,$type,0,0,$num);
            $sku[$kk]['price'] = $return['price'];
            $sku[$kk]['discount'] = $return['discount'];
            $sku[$kk]['discount_info'] = $return['discount_info'];
        }
        if(isset($sku[$kk]['unit']) && is_array($sku[$kk]['unit']))    $sku[$kk]['unit'] = $sku[$kk]['unit']['group_detail_name'];
        unset($sku[$kk]['discount_detail']);
    }
    return $sku;
}
//https请求,可以设置header头
function https_curl($url, $data, $headers = array())
{

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
//        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    }

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    $output = curl_exec($curl);

    curl_close($curl);

    return json_decode($output,true);
}
function sendvoice($data)
{
    $url = "http://iot.solomo-info.com:9306/admin/common/msgpush";
    $data['agent_id'] = '202007291001';
    $data['agent_secret'] = '11476900311476900311476900311111';
    $data['debug'] = 1;
    $header = array(
        "Content-Type: application/json;charset=utf-8",
    );
    $res = https_curl($url, $data, $header);
    return $res;
}
/*获取商品购买后的结束时间*/
function goodsEndTime($goods,$order){
    //到期时间
    $goods->is_effect = 0;
    $goods->start_time = null;
    $goods->end_time = null;
    if($goods->use_type == 1 && $order->pay_time){
        $goods->start_time = $goods->end_time = '永久有效';
        $goods->is_effect = 1;

    }
    if($goods->use_type == 2 && $order->pay_time){
        $pay_time = date('Y-m-d',$order->pay_time);
        if($goods->use_time_type == 1){
            $goods->start_time = date('Y-m-d H:i:s',$order->pay_time);
            $goods->end_time = date("Y-m-d",strtotime($pay_time) + $goods->use_time_num * 86400)." 23:59:59";
        }else{
            $goods->start_time = date('Y-m-d H:i:s',$order->pay_time);
            $goods->end_time = GetMonth($order->pay_time,$goods->use_time_num);

        }
    }
    if($goods->use_type == 3 && $order['pay_time']){
        $goods->start_time = $goods->use_start_time;
        $goods->end_time = $goods->use_end_time;
    }
    if(in_array($goods->use_type,[2,3])){
        if(time()>=strtotime($goods->start_time) && time()<=strtotime($goods->end_time)){
            $goods->is_effect = 1;
        }
    }
    return $goods;
}
function GetMonth($time,$sign)
{
    //判断当天是否为月最后一天
    if(date("t",$time)==date("d",$time)){
        //得到系统的年月
        $tmp_date=date("Ym",$time);
        //切割出年份
        $tmp_year=substr($tmp_date,0,4);
        //切割出月份
        $tmp_mon =substr($tmp_date,4,2);
        // 得到当前月份的下几月
        $tmp_nextmonth=mktime(0,0,0,$tmp_mon+$sign,1,$tmp_year);
        // 得到当前月份的前几月
        $tmp_forwardmonth=mktime(0,0,0,$tmp_mon-$sign,1,$tmp_year);

        return $fm_next_month=date("Y-m-t",$tmp_nextmonth).' 23:59:59';
    }else{
        return date("Y-m-d",strtotime("+$sign months",$time)).' 23:59:59';
    }


}
/*根据当前用户等级匹配价格(登录的用户才会有等级匹配的价格)*/
function getMemberDiscount($member,$shop_id,$vip_discount_type,$discount_detail){
    //默认无折扣
    $discount = 0;
    if($member && $discount_detail){
        //获取用户在当前门店的等级
        $level = MemberLevelModel::where(['member_id'=>$member->member_id,'shop_id'=>$shop_id,'is_delete'=>0])->find();
        if($level){
            if($level->level_id>0){
                for ($i=0;$i<count($discount_detail);$i++){
                    if($discount_detail[$i]['level_id']==$level->level_id){
                        if($vip_discount_type==1){
                            $discount = $discount_detail[$i]['member_price'];
                        }
                        if($vip_discount_type==2){
                            $discount = $discount_detail[$i]['bid_price'];

                        }
                        if($vip_discount_type==3){
                            $discount = $discount_detail[$i]['reduce_price'];
                        }
                    }
                }
            }

        }
    }
    return $discount;
}
/**
 * 根据当前用户等级匹配价格(登录的用户才会有等级匹配的价格)
 * hx_price划线价
*/
function getMemberPrice($member,$shop_id,$goods,$hx_price=0,$type=3,$pmid=0,$taId=0,$num=1){
    $return = [];$discount_info = '';
    //默认无折扣
    $price = ($goods['origin_type']==1 && $type==3)?$goods['original_price']:$goods['crossed_price'];
    if($member && $goods){
        $select_setting = LevelSettingModel::where(['shop_id'=>$shop_id,'is_selected'=>1])->find();
        //获取用户在当前门店的等级
        $where1 = $where2 = [
            ['member_id','=',$member['member_id']],
            ['shop_id','=',$shop_id],
            ['is_delete','=',0],
        ];
        $where1[]=['vip_start_time','<=',date('Y-m-d H:i:s')];
        $where1[]=['vip_end_time','>=',date('Y-m-d H:i:s')];
        $where1[]=['vip_time_type','<>',2];
        $where2[]=['vip_time_type','=',2];
        $level = MemberLevelModel::whereOr([$where1,$where2])->find();
        if($select_setting['type']>0 && $level){
            $shop_level = LevelModel::where(['shop_id'=>$shop_id,'level_id'=>$level->level_id,'is_delete'=>0,'type'=>$select_setting['type']])->find();
            if($shop_level && $level->level_id>0 && $goods['vip_discount_type']>0 && $goods['discount_detail']){
                for ($i=0;$i<count($goods['discount_detail']);$i++){
                    if($goods['discount_detail'][$i]['level_id']==$level->level_id){
                        if($goods['vip_discount_type']==1){
                            $price = $hx_price*($goods['discount_detail'][$i]['member_price']/10);
                            $discount_info = '会员专享：'.$goods['discount_detail'][$i]['member_price'].'折-¥'.sprintf("%.2f",($hx_price-$price)*$num);
                        }
                        if($goods['vip_discount_type']==2){
                            $price = $goods['discount_detail'][$i]['bid_price'];
                            $discount_price = floatval($hx_price)-floatval($price);
                            $discount_price = $discount_price * $num;
                            $discount_info = '会员专享：指定价格'.$price.'-¥'.sprintf("%.2f",$discount_price);
                        }
                        if($goods['vip_discount_type']==3){
                            $price = $hx_price-$goods['discount_detail'][$i]['reduce_price'];
                            $discount_info = '会员专享：减价'.$goods['discount_detail'][$i]['reduce_price'].'-¥'.sprintf("%.2f",($hx_price-$price)*$num);
                        }
                    }
                }
            }

        }
    }
    //是否是推广产品
    if($pmid>0 && $taId>0){
        $t_a = TeamActivityModel::where(['team_activity_id'=>$taId,'status'=>1,'is_delete'=>0])->find();
        if($t_a){
            $activte = ActivityModel::where(['activity_id'=>$t_a['activity_id'],'type'=>1,'status'=>1,'is_delete'=>0])->find();
            if(!empty($activte)) $price = $activte['price'];
        }

    }
    $return['price'] = sprintf("%.2f",$price);
    $return['discount'] = $hx_price<1?0:sprintf("%.2f",($price/$hx_price)*10);
    $return['discount_info'] = $discount_info;
    return $return;
}
//指定元素前移一位
function array_swap_forward($arr,$elem)
{
    $ndx = array_search($elem,$arr) - 1;
    $b4 = array_slice($arr,0,$ndx);
    $mid = array_reverse(array_slice($arr,$ndx,2));
    $after = array_slice($arr,$ndx + 2);

    return array_merge($b4,$mid,$after);
}
//指定元素后移一位
function array_swap_back($arr,$elem)
{
    $ndx = array_search($elem,$arr);
    $b4 = array_slice($arr,0,$ndx);
    $mid = array_reverse(array_slice($arr,$ndx,2));
    $after = array_slice($arr,$ndx + 2);

    return array_merge($b4,$mid,$after);
}
function reward_money($where){
    $consume=new ConsumeBonusSettingModel();
    $s=[];
    $s['shop_id']=$where['shop_id'];
    $reward_money=0;
    $shop_set=$consume->where($s)->find();
    if(empty($shop_set)) return $reward_money;
    if($shop_set['is_open']==1){
        $old_start=date('Y-m-d',$where['start_time']);
        $old_end=date('Y-m-d',$where['end_time']);
        $settle_w=[];
        $settle_w[]=['shop_id','=',$where['shop_id']];
        $settle_w[]=['settle_time','>=',$old_start];
        $settle_w[]=['settle_time','<=',$old_end];
        $consume_money=SettleOrderModel::where($settle_w)->sum('consume_money');
        $where['start_time']=strtotime(date('Y-m-d 00:00:00'));
        $where['end_time']=strtotime(date('Y-m-d 23:59:59'));
        $where['status']=8;
        $uo_info=GoodsOrderModel::user_order($where);
        $where['status']=1;
        $ub_info=BuyOrderModel::user_order($where);
//        $pin_info=PinTuanOrderModel::user_order($where);
        if($shop_set['bonus_budget_type']==1){
            $reward_money=$uo_info['money']*($shop_set['bonus_budget']/100)+$ub_info['money']*($shop_set['bonus_budget']/100);
        }elseif ($shop_set['bonus_budget_type']==2){
            $reward_money=$ub_info['money']*($shop_set['buy_bonus_budget']/100)+$uo_info['all_goods_gross']*($shop_set['normal_bonus_budget']/100);
        }
        $reward_money=$reward_money+$consume_money;
        if ($shop_set['bonus_cycle']==2){//两次奖励
            $config=DataConfigModel::where(['id'=>1])->find();
            $bonus1=$config['bonus1'];
            $bonus2=$config['bonus2'];
            switch ($shop_set['bonus_cycle_type']){
                case 1:
                    $type_arr[1]=$bonus1;
                    $type_arr[2]=$bonus2;
                    break;
                case 2:
                    $type_arr[2]=$bonus1;
                    $type_arr[3]=$bonus2;
                    break;
                case 3:
                    $type_arr[2]=$bonus1;
                    $type_arr[4]=$bonus2;
                    break;
                case 4:
                    $type_arr[3]=$bonus1;
                    $type_arr[4]=$bonus2;
                    break;
                case 5:
                    $type_arr[3]=$bonus1;
                    $type_arr[5]=$bonus2;
                    break;
                default:
                    $type_arr=[];
                    break;
            }
            if(!empty($type_arr)){
                $ratio=empty($type_arr[$where['type']])?1:($type_arr[$where['type']]/100);
                $reward_money=$reward_money*$ratio;
            }
        }
    }
    return round($reward_money,2);
}
function partner_reward_money($where){
    $partnerbonus=new PartnerBonusSettingModel();
    $s=[];
    $s['shop_id']=$where['shop_id'];
    $s['is_delete']=0;
    $reward_money=0;
    $shop_set=$partnerbonus->where($s)->find();
    $old_start=date('Y-m-d',$where['start_time']);
    $old_end=date('Y-m-d',$where['end_time']);
    $settle_w=[];
    $settle_w[]=['shop_id','=',$where['shop_id']];
    $settle_w[]=['settle_time','>=',$old_start];
    $settle_w[]=['settle_time','<=',$old_end];
    $partner_bonus=SettleOrderModel::where($settle_w)->sum('partner_bonus');
    $where['start_time']=strtotime(date('Y-m-d 00:00:00'));
    $where['end_time']=strtotime(date('Y-m-d 23:59:59'));
    $where['status']=8;
    $uo_info=GoodsOrderModel::user_order($where);
    $where['status']=1;
    $ub_info=BuyOrderModel::user_order($where);
    if($shop_set['bonus_budget_type']==1){
        $reward_money=$uo_info['money']*($shop_set['bonus_budget']/100)+$ub_info['money']*($shop_set['bonus_budget']/100);
    }elseif ($shop_set['bonus_budget_type']==2){
        $reward_money=$uo_info['all_goods_gross']*($shop_set['normal_bonus_budget']/100)+$ub_info['money']*($shop_set['buy_bonus_budget']/100);
    }
    $reward_money=$reward_money+$partner_bonus;
    return round($reward_money,2);
}
function verifyMemberLevel($shop_id,$member_id){
    $level = MemberLevelModel::where(['shop_id'=>$shop_id,'member_id'=>$member_id,'is_delete'=>0])->find();
    return $level;
}

function saveMemberLevel($shop_id,$member_id){
    if($member_id && $shop_id){
        $level = MemberLevelModel::where(['member_id'=>$member_id,'shop_id'=>$shop_id,'is_delete'=>0])->find();
        if(empty($level)){
            $member_model = new MemberLevelModel();
            $member_model->shop_id = $shop_id;
            $member_model->member_id = $member_id;
            $member_model->save();
        }
    }

}
/*删除购物车*/
function delCart($goods,$member_id,$shop_id){
    $cart_ids = [];
    $cart_model = new \app\stores\model\cart\CartModel();
    foreach ($goods as $k=>$v){
        $cart = $cart_model->getCart(['is_delete'=>0,'shop_id'=>$shop_id,'goods_id'=>$v['goods_id'],'sku_id'=>$v['sku_id'],'member_id'=>$member_id]);
        if($cart) $cart_ids[] = $cart['cart_id'];
    }
    if($cart_ids){
        $where[]=['cart_id','in',$cart_ids];
        $cart_model->saveCart($where,['is_delete'=>1]);
    }

    return true;

}
/*获取门店的会员*/
function shopMembers($shop_id){
    $member_ids = [];
    $member_arr = MemberLevelModel::where(['shop_id'=>$shop_id,'is_delete'=>0])->select()->toArray();
    if($member_arr){
        $member_ids = array_column($member_arr,'member_id');
    }
    return $member_ids;
}
/*获取门店的锁客会员*/
function shopMemberlock($shop_id){
    $member_ids = [];
    $member_arr = MemberLockModel::where(['shop_id'=>$shop_id])->select()->toArray();
    if($member_arr){
        $member_ids = array_column($member_arr,'member_id');
    }
    return $member_ids;
}
/*生成订单号*/
function createOrderSn($order_id,$type=1){
    //type1商城2买单3拼团4秒杀5退款6付费会员7收银
    return date('YmdHis') .$type. $order_id;
}
function addSearch($member_id,$content=''){
    if($content){
        $search_model = new MemberSearchModel();
        $search_model->save(['member_id'=>$member_id,'content'=>$content]);
    }

}
function getMemberLevel($member_id,$shop_id){
    $level_setting = LevelSettingModel::where(['is_selected'=>1,'shop_id'=>$shop_id])->find();
    if(!empty($level_setting) && $level_setting['type']>0){
        //获取用户在当前门店的等级
        $where1 = $where2 = [
            ['member_id','=',$member_id],
            ['shop_id','=',$shop_id],
            ['is_delete','=',0],
        ];
        $where1[]=['vip_start_time','<=',date('Y-m-d H:i:s')];
        $where1[]=['vip_end_time','>=',date('Y-m-d H:i:s')];
        $where1[]=['vip_time_type','<>',2];
        $where2[]=['vip_time_type','=',2];
        $level = MemberLevelModel::where(['member_id'=>$member_id,'shop_id'=>$shop_id,'is_delete'=>0])
            ->whereOr([$where1,$where2])
            ->find();
        if($level){
            $shop_level = LevelModel::where(['shop_id'=>$shop_id,'is_delete'=>0,'level_id'=>$level->level_id,'type'=>$level_setting['type']])->find();
            if($shop_level){
                return $level->level_id;
            }

        }
    }
    return 0;
}
function isBuyMember($member_id,$shop_id){
    $is_buy_member = 0;
    $level_setting = LevelSettingModel::where(['is_selected'=>1,'shop_id'=>$shop_id])->find();
    if(!empty($level_setting) && $level_setting['type']>0){
        $level = LevelModel::where(['is_delete'=>1,'shop_id'=>$shop_id,'type'=>$level_setting['type']])->select();
        if(!empty($level)){
            $level_id = getMemberLevel($member_id,$shop_id);
            if($level_id>0) $is_buy_member = 1;
        }
    }
    return $is_buy_member;
}
/**
 * 订单推广提成
 * @param $order_id
 * @param $type  订单类型：0普通订单，1买单订单,2拼团订单
 */
function order_bonus($order_id,$type=0){
    $order_money=0;
    $goods_gross=0;
    $commission=0;
    $order_status=0;
    $money_status=0;
    if($type==0){//普通订单
        $order=GoodsOrderModel::where(['order_id'=>$order_id,'is_paid'=>1,'from_type'=>2])->find();
    }elseif($type==1){
        $order=BuyOrderModel::where(['buy_order_id'=>$order_id,'is_paid'=>1,'from_type'=>2])->find();
    }
//    elseif($type==2){
//        $order=PinTuanOrderModel::where(['pin_tuan_order_id'=>$order_id,'is_paid'=>1,'from_type'=>2])->find();
//    }
    if (empty($order)) return false;//订单不存在
    if($type==0){
        $order_money=$order['need_pay'];
        $goods_gross=$order['all_goods_gross'];
        $order_status=$order['status'];
    }elseif($type==1){
        $order_money=$order['pay_money'];
        $order_status=8;
    }
//    elseif($type==2){
//        $order_money=$order['need_pay'];
//        $goods_gross=$order['all_goods_gross'];
//        if($order['status']==3){
//            $order_status=8;
//        }
//    }
    $member_id=$order['member_id'];
    $shop_id=$order['shop_id'];
    $member_info=MemberModel::where(['member_id'=>$member_id])->find();
    if (empty($member_info['pid'])) return false;//用户不是推广用户
    $pid=$member_info['pid'];
    $where=[];
    $where['shop_id']=$shop_id;
    $where['member_id']=$pid;
    $partner_info=PartnerModel::info($where,[]);
    if(empty($partner_info)) return false;//股东不存在
    $partner_id=$partner_info['partner_id'];
    $setting=PartnerPromotionSettingModel::where(['shop_id'=>$shop_id,'is_delete'=>0])->find();
    if(empty($setting)) return false;//门店推广分成配置未开启
    if($setting['dividend_type']==1){//订单金额
        $commission=round($order_money*($partner_info['ratio']/100),2);
    }elseif ($setting['dividend_type']==2){//按毛利分成
        if($type==0 || $type==2){
            $commission=round($goods_gross*($partner_info['ratio']/100),2);
        }elseif($type==1){
            $commission=round($order_money*($partner_info['buy_ratio']/100),2);
        }
    }
//    var_dump($partner_info);
//    var_dump($commission);exit();
    if(empty($commission)) return false;//提成金额为0 或者不存在
    if($order_status==8){//订单已完成
        $in_commission=[];
        $in_commission['shop_id']=$shop_id;
        $in_commission['partner_id']=$partner_id;
        $in_commission['member_id']=$member_id;
        $in_commission['month']=date('Y-m',time());
        $in_commission['monetary']=$order_money;
        $in_commission['commission']=$commission;
        $in_commission['description']=$commission;
        $in_commission['order_id']=$order_id;
        $in_commission['date']=date('Y-m-d H:i:s',time());
        if($type==0){
            $in_commission['type']='普通订单';
        }elseif ($type==1){
            $in_commission['type']='买单订单';
        }elseif ($type==2){
            $in_commission['type']='拼团订单';
        }
        PartnerCommissionModel::insert($in_commission);//写入推广提成明细
        $money_status=0;
    }
    MemberMoneyDetailModel::in($commission,1,4,$shop_id,$partner_info['member_id'],$partner_id,$order_id,$type,$money_status);//写入钱包明细
}
function promotion_money($team_activity_id,$order_id,$num=0,$settle_type){
    $team_activity = TeamActivityModel::where(['team_activity_id'=>$team_activity_id,'status'=>1,'is_delete'=>0])->find();
    if($team_activity){
        $activity = ActivityModel::where(['activity_id'=>$team_activity->activity_id,'status'=>1,'is_delete'=>0])->find();
        if($activity && $activity['settle_type']==$settle_type){
            promotion_bonus($order_id);
        }
    }

}
/**
 * 地推订单推广提成
 * @param $order_id
 */
function promotion_bonus($order_id){
    $money_status=0;
    $order=GoodsOrderModel::where(['order_id'=>$order_id,'is_paid'=>1,'from_type'=>2])->find();
    if (empty($order)) return false;//订单不存在
    $order_status=$order['status'];
    $p_mid=$order['p_mid'];
    $team_id=$order['team_id'];
    $team_activity_id=$order['team_activity_id'];
    $p_s=[];
    $p_s['is_delete']=0;
    $p_s['member_id']=$p_mid;
    $p_s['type']=1;
    $p_s['team_id']=$team_id;
    $member_info=PromotionmemberModel::where($p_s)->find();
    if (empty($member_info)) return false;//推广用户不存在
    $t_s=[];
    $t_s['team_activity_id']=$team_activity_id;
    $t_s['status']=1;
    $t_s['is_delete']=0;
    $team_activity_info=TeamActivityModel::where($t_s)->find();
    if (empty($team_activity_info)) return false;//团队推广活动不存在
    $a_s=[];
    $a_s['activity_id']=$team_activity_info['activity_id'];
    $a_s['status']=1;
    $a_s['is_delete']=0;
    $activity_info=ActivityModel::where($a_s)->find();
    if (empty($activity_info)) return false;//推广活动不存在
    if($activity_info['settle_type']==1){//实时结算
        $money_status=1;
    }elseif($activity_info['settle_type']==2){//核销后结算
        $money_status=0;
    }
    $p_money=$team_activity_info['team_commission'];
    $t_money=$activity_info['commission']-$team_activity_info['team_commission'];
    if(empty($t_money) && empty($p_money)) return false;//提成金额为0 或者不存在
    if($order_status==8){//订单已完成
        $money_status=1;
    }
    PromotionmoneydetailModel::in($p_money,1,$p_mid,$team_id,$order_id,$money_status);//写入推广员钱包明细，个人业绩
    PromotionmoneydetailModel::in($t_money,1,0,$team_id,$order_id,$money_status);//写入推广团队钱包明细，团队业绩
}
function memberNum($length)
{
    $str = memberNumStr($length);
    $member = new MemberModel();
    $m = $member->getById(['member_num'=>$str,'is_delete'=>0]);
    if($m){
        $str = memberNum($length);
    }
    return $str;
}

function memberNumStr($length)
{
    $str = '';
    for($i=0;$i<$length;$i++){
        $str .= mt_rand(0,9);
    }
    return $str;
}

/**
 * @param $order_id
 * @param $type  1下单id，2买单id
 */
function memberlock($order_id,$type){
    $money=0;
    $shop_id=0;
    if($type==1){
        $order_info=GoodsOrderModel::where(['order_id'=>$order_id])->find();
        if (!empty($order_info)) {
            $money=$order_info['need_pay'];
            $shop_id=$order_info['shop_id'];
            $member_id=$order_info['member_id'];
        }
    }elseif($type==2){
        $order_info=BuyOrderModel::where(['buy_order_id'=>$order_id])->find();
        if (!empty($order_info)) {
            $money=$order_info['pay_money']-$order_info['refund_money'];
            $shop_id=$order_info['shop_id'];
            $member_id=$order_info['member_id'];
        }
    }
    if(empty($money)) return '';
    $config=DataConfigModel::where(['id'=>1])->find();
    if($config['is_lock']==0){//锁客分红关闭
        return '';
    }
    $locksetting=json_decode($config['lock_setting'],true);
    $lock_money=round($money*$config['lock_ratio']/100,2);
    $member=MemberModel::where(['member_id'=>$member_id])->find();
    $lock_ratio=0;
    foreach ($locksetting as $lock_v){
        if($lock_v['max']>0){
            if($money>=$lock_v['min'] && $money<=$lock_v['max']){
                $lock_ratio=$lock_v['ratio'];
            }
        }else{
            if($money>=$lock_v['min']){
                $lock_ratio=$lock_v['ratio'];
            }
        }
    }
    $lock_in=[];
    $lock_in['member_id']=$member_id;
    $lock_in['shop_id']=$shop_id;
    $l_s=[];
    $l_s['shop_id']=$shop_id;
    $l_s['member_id']=$member_id;
    if($type==1){
        $lock_in['order_id']=$order_id;
//        $l_s['order_id']=$order_id;
    }elseif($type==2){
        $lock_in['buy_order_id']=$order_id;
//        $l_s['buy_order_id']=$order_id;
    }
    $lock_in['need_pay']=$money;
    $lock_in['from_type']=2;
    $lock_in['add_time']=date('Y-m-d H:i:s');
    if($member['lock_shop_ratio']>=100){//已被完全锁定
        $lock_list=MemberLockModel::where(['member_id'=>$member_id])->select()->toArray();
        if(empty($lock_list)) return '';
        foreach ($lock_list as $l_v){
            $s_lock_money=round($lock_money*$l_v['share_ratio']/100,2);
            if($s_lock_money>0){
                ShopBalanceLogsModel::in($s_lock_money,1,$l_v['shop_id'],$order_id,$type);
            }
        }
    }elseif ($member['lock_shop_ratio']>0 && $member['lock_shop_ratio']<100){
        $lock_list=MemberLockModel::where([['member_id','=',$member_id]])->select()->toArray();
        $share_ratio=0;
        foreach ($lock_list as $l_v){
            $share_ratio+=$l_v['share_ratio'];
            $s_lock_money=round($lock_money*$l_v['share_ratio']/100,2);
            if($s_lock_money>0) {
                ShopBalanceLogsModel::in($s_lock_money, 1, $l_v['shop_id'], $order_id, $type);
            }
        }
        if((100-$share_ratio)<$lock_ratio){
            $lock_ratio=100-$share_ratio;
        }
        $lock_in['share_ratio']=$lock_ratio;
        $l_info=MemberLockModel::where($l_s)->find();
        if($lock_ratio>0){
            if(empty($l_info)){
                MemberLockModel::insertGetId($lock_in);
            }else{
                $lock_in['share_ratio']=100;
                unset($lock_in['add_time']);
                MemberLockModel::update($lock_in,['member_lock_id'=>$l_info['member_lock_id']]);
            }
            MemberModel::update(['lock_shop_ratio'=>$member['lock_shop_ratio']+$lock_ratio],['member_id'=>$member_id]);
        }
        $s_lock_money=round($lock_money*$lock_ratio/100,2);
        if($s_lock_money>0) {
            ShopBalanceLogsModel::in($s_lock_money, 1, $shop_id, $order_id, $type);
        }
    }elseif ($member['lock_shop_ratio']==0){
        $lock_in['share_ratio']=$lock_ratio;
        $l_info=MemberLockModel::where($l_s)->find();
        if(empty($l_info) && $lock_ratio>0){
            MemberLockModel::insertGetId($lock_in);
            MemberModel::update(['lock_shop_ratio'=>$member['lock_shop_ratio']+$lock_ratio],['member_id'=>$member_id]);
        }
        $s_lock_money=round($lock_money*$lock_ratio/100,2);
        if($s_lock_money>0) {
            ShopBalanceLogsModel::in($s_lock_money, 1, $shop_id, $order_id, $type);
        }
    }
}
/*结算明细退款统计*/
function refundTj($settlement,$shop_id){
    $b_order_ids = settleOrderModel::where(['settle_id'=>$settlement->settlement_id])->where('b_order_id','>',0)->column('b_order_id');
    $order_ids = settleOrderModel::where(['settle_id'=>$settlement->settlement_id])->where('order_id','>',0)->column('order_id');

    $where[]=[
        ['shop_id','=',$shop_id],
        ['status','=',1],
        ['is_delete','=',0]
    ];
    $o_refund = OrderRefundModel::where($where)->where(['refund_type'=>1])->whereIn('order_id',$order_ids)->field('count(*) as count,sum(refund_price) as refund_money')->find();
    $b_refund = OrderRefundModel::where($where)->where(['refund_type'=>1])->whereIn('buy_order_id',$b_order_ids)->field('count(*) as count,sum(refund_price) as refund_money')->find();

    //全额退款
    $o_all_refund_money = $o_refund->refund_money;
    $b_all_refund_money = $b_refund->refund_money;
    $o_all_refund_count = $o_refund->count;
    $b_all_refund_count = $b_refund->count;

    //部分退款
    $o_bf_refund_count = OrderRefundModel::where($where)->where(['refund_type'=>2])->whereIn('order_id',$order_ids)->group('order_id')->count();
    $b_bf_refund_count = OrderRefundModel::where($where)->where(['refund_type'=>2])->whereIn('buy_order_id',$b_order_ids)->group('buy_order_id')->count();
    $o_bf_refund_money = OrderRefundModel::where($where)->where(['refund_type'=>2])->whereIn('order_id',$order_ids)->sum('refund_price');
    $b_bf_refund_money = OrderRefundModel::where($where)->where(['refund_type'=>2])->whereIn('buy_order_id',$b_order_ids)->sum('refund_price');

    //流水金额
    $o_total_price = \app\beautiful\model\order\GoodsOrderModel::where(['is_delete'=>0])->whereIn('order_id',$order_ids)->where(['shop_id'=>$shop_id,'is_paid'=>1])->sum('total_price');
    $b_total_price = \app\stores\model\order\BuyOrderModel::whereIn('buy_order_id',$b_order_ids)->where(['shop_id'=>$shop_id,'is_paid'=>1])->sum('balance');

    //储值卡支付
    $o_money_total_price = \app\beautiful\model\order\GoodsOrderModel::where(['is_delete'=>0])->whereIn('order_id',$order_ids)->where(['shop_id'=>$shop_id,'is_paid'=>1])->sum('money');
    $b_money_total_price = \app\stores\model\order\BuyOrderModel::whereIn('buy_order_id',$b_order_ids)->where(['shop_id'=>$shop_id,'is_paid'=>1])->sum('money');
    //储值卡退款
    $o_money_refund_money = OrderRefundModel::where($where)->whereIn('order_id',$order_ids)->sum('refund_money');
    $b_money_refund_money = OrderRefundModel::where($where)->whereIn('buy_order_id',$b_order_ids)->sum('refund_money');

    $return['refund_money'] = sprintf("%.2f",$o_all_refund_money + $b_all_refund_money + $b_bf_refund_money + $o_bf_refund_money);
    $return['all_refund_count'] = $o_all_refund_count + $b_all_refund_count;
    $return['bf_refund_count'] = $b_bf_refund_count + $o_bf_refund_count;
    $return['order_pay_price'] = $o_total_price + $b_total_price;
    $return['total_money'] = sprintf("%.2f",$o_money_total_price + $b_money_total_price - $o_money_refund_money - $b_money_refund_money);
    return $return;
}
/*
* 微信回调混合支付
*type(1买单2普通订单3付费会员订单4拼团订单)
*/
function mix_pay_money($order,$payInfo,$order_type){

    $is_refund = 0;
    $error = '';
    if(!empty($order->mix_pay_type)){
        $member = MemberModel::where(['member_id'=>$order->member_id])->find();

        $balance = MemberBalanceModel::where([
                ['shop_id','=',$order->shop_id],
                ['member_id','=',$order->member_id],
                ['valid_bg_time','<=',time()]
            ])->sum('remain_balance') ?? 0;

        $mix_pay_type = explode(',',$order->mix_pay_type);

        //先判断在扣除
        if(in_array('platform_money',$mix_pay_type) && ($order->platform_money<=0 || $member->money<$order->platform_money)){
            $error = '钱包余额不足或订单异常';
            $is_refund = 1;
        }

        if(in_array('money',$mix_pay_type) && ($order->money<=0 || $balance<$order->money)){
            $error = '储值卡余额不足或订单异常';
            $is_refund = 1;
        }
        if($is_refund!=1 && in_array('platform_money',$mix_pay_type) && $order->platform_money>0){
            if($member->money >= $order->platform_money) {
                $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($order->shop_id, $order->member_id);

                if($order_type==1){
                    $res = $StoresMemberWalletLogic->usePlatformMoney($order->platform_money, $order->buy_order_id,0,0,2);
                }else if($order_type==4){
                    $res = $StoresMemberWalletLogic->usePlatformMoney($order->platform_money, 0, 0, $order->pin_tuan_order_id, 1); //商城购物使用
                }else if($order_type==3){
                    $res = $StoresMemberWalletLogic->usePlatformMoney($order->platform_money, 0, 0,0, 25,$order->order_id);
                }else{
                    $type = $order->order_type == 'flash_sale'?7:1;
                    $res = $StoresMemberWalletLogic->usePlatformMoney($order->platform_money, 0 , $order->order_id,0,$type); //商城购物使用
                }
            }

            if((isset($res) && $res == false) || $member->money<$order->platform_money){
                //钱包不足，微信需要自动退款
                $error = '钱包余额不足或订单异常';
                $is_refund = 1;

            }

        }
        if($is_refund!=1 && in_array('money',$mix_pay_type) && $order->money>0){
            if($balance>=$order->money) {
                $MemberWalletLogic = new \app\stores\logic\MemberWalletLogic($order->shop_id, $order->member_id);
                if($order_type==3){
                    $type_id = 25;
                }else{
                    $type_id = $order_type==1?5:8;
                }
                $res = $MemberWalletLogic->useBalance($order->money, $order->money , $type_id); //商城购物使用
            }

            if((isset($res) && $res == false) || $balance<$order->money){
                //储值卡不足，微信需要自动退款
                $error = '储值卡余额不足或订单异常';
                $is_refund = 1;

            }
        }
        if($is_refund==1){
            //微信支付原路退还
            if($payInfo){
                $pay_info = $payInfo;
                $pay_info['refund_total_fee'] = $order->weixin * 100;
                $pay_info['out_refund_no'] = $refund_order_sn = createOrderSn($order->order_id,1);
                $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($order->shop_id);
                $re= $PaymentGoodsOrderHelper->refundInTheSameWayBf($pay_info);
                if($re['result_code']=='FAIL'){

                }else{
                    $order_refund = new OrderRefundModel();
                    $order_refund->refund_order_sn = $refund_order_sn;
                    $order_refund->shop_id = $order->shop_id;
                    if($order_type==1)  $order_refund->buy_order_id = $order->buy_order_id;
                    if($order_type!=1)  $order_refund->order_id = $order->order_id;
                    $order_refund->member_id = $order->member_id;
                    $order_refund->refund_price = $order->weixin;
                    $order_refund->refund_weixin = $order->weixin;
                    $order_refund->pay_money = $order->weixin;
                    $order_refund->status = 1;
                    $order_refund->reason = '混合支付失败原路退回';
                    $order_refund->refund_type = 1;
                    $order_refund->update_time = date('Y-m-d H:i:s');
                    $order_refund->operate_id = 0;
                    $order_refund->save();
                }
            }

            //修改订单状态
            if($order_type==1){
                $update_data['status'] = 4;
                if($payInfo) $update_data['real_money'] = $order->weixin;
                if($re['result_code']!='FAIL') $update_data['reason'] = '混合支付失败原路退回';
                if($re['result_code']!='FAIL') $update_data['refund_money'] = $order->weixin;
                $update_data['edit_time'] = date('Y-m-d H:i:s');
                \app\stores\model\order\BuyOrderModel::where(['buy_order_id'=>$order->buy_order_id])->save($update_data);
            }else{
                $update_data['status'] = 14;
                if($payInfo) $update_data['real_money'] = $order->weixin;
                $update_data['edit_time'] = date('Y-m-d H:i:s');
                \app\stores\model\order\GoodsOrderModel::where(['order_id'=>$order->order_id])->save($update_data);
            }
        }
    }
    $return['error'] = $error;
    $return['is_refund'] = $is_refund;
    return $return;

}
/*混合支付*/
function checkPayWay($params,$need_pay,$member_id,$shop_id){
    $mix_pay_money = [];
    $error = '';
    if(!empty($params['mix_pay_type'])){
        if(count($params['mix_pay_type'])<2) $error = '混合支付必须要两种及以上支付方式';
        $remain_money = $need_pay;
        if(in_array('balance',$params['mix_pay_type'])){
            $balance = MemberBalanceModel::where([
                    ['shop_id','=',$shop_id],
                    ['member_id','=',$member_id],
                    ['valid_bg_time','<=',time()]
                ])->sum('remain_balance') ?? 0;

            if($balance<=0)  $error = '储值卡余额0，不能选择哦';
            if($remain_money > $balance){
                $remain_money = sprintf("%.2f",$remain_money - $balance);
                $mix_pay_money['money'] = $balance;
            }else{
                $mix_pay_money['money'] = $remain_money;
                $remain_money = 0;
            }
        }

        if($remain_money===0 && in_array('money',$params['mix_pay_type'])) $error = '储值卡金额已够，不能选混合支付';

        if(in_array('money',$params['mix_pay_type']) && $remain_money>0){
            $member = MemberModel::find($member_id);
            if(empty($member))  $error = '用户不存在';
            if($member->money<=0)  $error = '钱包余额0，不能选择哦';

            if($remain_money > $member['money']){
                $remain_money = sprintf("%.2f",$remain_money - $member['money']);
                $mix_pay_money['platform_money'] = $member['money'];
            }else{
                $mix_pay_money['platform_money'] = $remain_money;
                $remain_money = 0;
            }

        }

        if($remain_money>0 && !in_array('weixin',$params['mix_pay_type'])) $error = '需要选择微信支付';

        if($remain_money<=0 && in_array('weixin',$params['mix_pay_type'])) $error = '不需要选择微信支付';

        if($remain_money>0 && in_array('weixin',$params['mix_pay_type'])){
            $mix_pay_money['weixin'] = $remain_money;
        }
    }
    $return['mix_pay_money'] = $mix_pay_money;
    $return['error'] = $error;
    return $return;
}
/*混合支付退款*/
function mix_refund_money($order,$refund){
    $return['code'] = true;
    $return['error'] = '';

    $mix_pay_type = explode(',',$order['mix_pay_type']);

    if(in_array('weixin',$mix_pay_type) && $order['weixin']>0){
        //支付原路退还
        $pay_info = $order['pay_info'];
        $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($order['shop_id']);
        $re= $PaymentGoodsOrderHelper->refundInTheSameWay($pay_info);
        if($re['result_code']=='FAIL'){
            $return['code'] = false;
            $return['error'] = $re['err_code_des'];
        }
    }

    if(in_array('money',$mix_pay_type) && $order['money']>0){
        $MemberWalletLogic = new MemberWalletLogic($order['shop_id'], $order['member_id']);
        $res = $MemberWalletLogic->rebackBalance($refund->refund_money, 0 , 23); //商城购物使用
        if($res == false){
            $return['code'] = false;
            $return['error'] = $MemberWalletLogic->getError();
        }
    }

    if(in_array('platform_money',$mix_pay_type) && $order['platform_money']>0){
        $member = MemberModel::where(['member_id'=>$order['member_id']])->find();
        $money = $member->money;
        $member->money = $member->money+$refund->refund_platform_money;
        $member->save();
        LogsLogic::money($order['shop_id'], $order['member_id'], 23, 1, $money,$refund->refund_platform_money, $money+$refund->refund_platform_money,0,$order['order_id'],$order['pin_tuan_order_id']);
    }
    return $return;
}
/*混合支付部分退款*/
function buy_mix_refund_money($order,$buy_refund_money=0){
    $return['code'] = true;
    $return['error'] = '';
    $return['refund_money'] = $return['refund_platform_money'] = $return['refund_weixin'] = 0;
    if($buy_refund_money<=0){
        $return['code'] = false;
        $return['error'] = '退款金额不能为0';
        return $return;
    }
    //退款金额不能大于剩余金额
    if($buy_refund_money>($order->pay_money-$order->refund_money)){
        $return['code'] = false;
        $return['error'] = '退款金额不能大于'.$order->pay_money-$order->refund_money;
        return $return;
    }
    //储值卡已退金额
    $refund_money = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'buy_order_id'=>$order['buy_order_id'],'status'=>1,'is_delete'=>0])->sum('refund_money');
    //钱包已退金额
    $refund_platform_money = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'buy_order_id'=>$order['buy_order_id'],'status'=>1,'is_delete'=>0])->sum('refund_platform_money');
    //微信已退金额
    $refund_weixin = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'buy_order_id'=>$order['buy_order_id'],'status'=>1,'is_delete'=>0])->sum('refund_weixin');

    $mix_pay_type = explode(',',$order['mix_pay_type']);

    //是否有一次性退完的通道
    if(in_array('money',$mix_pay_type)){
        //储值卡可以退的钱
        $can_refund['money'] = $order->money - $refund_money;
    }
    if(in_array('platform_money',$mix_pay_type)){
        //钱包可以退的钱
        $can_refund['platform_money'] = $order->platform_money - $refund_platform_money;
    }
    if(in_array('weixin',$mix_pay_type)){
        //微信可以退的钱
        $can_refund['weixin'] = $order->weixin - $refund_weixin;
    }

    $remain_refund_money = $buy_refund_money;
    if(in_array('money',$mix_pay_type) && isset($can_refund['money']) && $can_refund['money']>0){
        $can_refund_money = $can_refund['money'];
        if($can_refund_money>0){
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['money'] = $can_refund_money;
            }else {
                $refund['money'] = $remain_refund_money;
                $remain_refund_money = 0;
            }

        }

    }
    if(in_array('platform_money',$mix_pay_type) && $remain_refund_money>0 && isset($can_refund['platform_money']) && $can_refund['platform_money']>0){
        $can_refund_money = $can_refund['platform_money'];
        if($can_refund_money>0) {
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['platform_money'] = $can_refund_money;
            }else {
                $refund['platform_money'] = $remain_refund_money;
                $remain_refund_money = 0;
            }


        }

    }
    if(in_array('weixin',$mix_pay_type) && $remain_refund_money>0  && isset($can_refund['weixin']) && $can_refund['weixin']>0){
        $can_refund_money = $can_refund['weixin'];
        if($can_refund_money>0) {
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['weixin'] = $can_refund_money;
            }else {
                $refund['weixin'] = $remain_refund_money;
                $remain_refund_money = 0;
            }
        }

    }
    if($remain_refund_money>0){
        $return['code'] = false;
        $return['error'] = '数据有误，请联系负责人';
        return $return;
    }
    if(isset($refund['money']) && $refund['money']){
        $MemberWalletLogic = new MemberWalletLogic($order['shop_id'], $order['member_id']);
        $res = $MemberWalletLogic->rebackBalance($refund['money'], 0 , 24); //商城购物使用
        if($res == false){
            $return['code'] = false;
            $return['error'] = $MemberWalletLogic->getError();

        }else{
            $return['refund_money'] = $refund['money'];
        }
    }
    if(isset($refund['platform_money']) && $refund['platform_money']){
        $member = MemberModel::where(['member_id'=>$order['member_id']])->find();
        $money = $member->money;
        $member->money = $member->money+$refund['platform_money'];
        $member->save();
        LogsLogic::money($order['shop_id'], $order['member_id'], 24, 1, $money,$refund['platform_money'], $money+$refund['platform_money'],$order['buy_order_id'],0,0);
        $return['refund_platform_money'] = $refund['platform_money'];
    }
    if(isset($refund['weixin']) && $refund['weixin']){
        $pay_info = $order['pay_info'];
        $pay_info['refund_total_fee'] = $refund['weixin'] * 100;
        $pay_info['out_refund_no'] = $refund_order_sn = createOrderSn($order['buy_order_id'],5);
        $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($order['shop_id']);
        $re= $PaymentGoodsOrderHelper->refundInTheSameWayBf($pay_info);
        if($re['result_code']=='FAIL'){
            $return['code'] = false;
            $return['error'] = $re['err_code_des'];

        }else{
            $return['refund_weixin'] = $refund['weixin'];
        }
    }
    return $return;
}
/*混合支付部分退款*/
function order_mix_refund_money($order,$order_refund_money=0){
    $return['code'] = true;
    $return['error'] = '';
    $return['refund_money'] = $return['refund_platform_money'] = $return['refund_weixin'] = 0;
    $pay_money = $order->need_pay;
    if($order_refund_money<=0){
        $return['code'] = false;
        $return['error'] = '退款金额不能为0';
        return $return;
    }
    //退款金额不能大于剩余金额
    if($order_refund_money>($pay_money-$order->refund_money)){
        $return['code'] = false;
        $return['error'] = '退款金额不能大于'.$pay_money-$order->refund_money;
        return $return;
    }
    //储值卡已退金额
    $refund_money = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'order_id'=>$order['order_id'],'status'=>1,'is_delete'=>0])->sum('refund_money');
    //钱包已退金额
    $refund_platform_money = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'order_id'=>$order['order_id'],'status'=>1,'is_delete'=>0])->sum('refund_platform_money');
    //微信已退金额
    $refund_weixin = OrderRefundModel::where(['shop_id'=>$order['shop_id'],'order_id'=>$order['order_id'],'status'=>1,'is_delete'=>0])->sum('refund_weixin');

    $mix_pay_type = explode(',',$order['mix_pay_type']);

    //是否有一次性退完的通道
    if(in_array('money',$mix_pay_type)){
        //储值卡可以退的钱
        $can_refund['money'] = $order->money - $refund_money;
    }
    if(in_array('platform_money',$mix_pay_type)){
        //钱包可以退的钱
        $can_refund['platform_money'] = $order->platform_money - $refund_platform_money;
    }
    if(in_array('weixin',$mix_pay_type)){
        //微信可以退的钱
        $can_refund['weixin'] = $order->weixin - $refund_weixin;
    }

    $remain_refund_money = $order_refund_money;
    if(in_array('money',$mix_pay_type) && isset($can_refund['money']) && $can_refund['money']>0){
        $can_refund_money = $can_refund['money'];
        if($can_refund_money>0){
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['money'] = $can_refund_money;
            }else {
                $refund['money'] = $remain_refund_money;
                $remain_refund_money = 0;
            }

        }

    }
    if(in_array('platform_money',$mix_pay_type) && $remain_refund_money>0 && isset($can_refund['platform_money']) && $can_refund['platform_money']>0){
        $can_refund_money = $can_refund['platform_money'];
        if($can_refund_money>0) {
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['platform_money'] = $can_refund_money;
            }else {
                $refund['platform_money'] = $remain_refund_money;
                $remain_refund_money = 0;
            }


        }

    }
    if(in_array('weixin',$mix_pay_type) && $remain_refund_money>0  && isset($can_refund['weixin']) && $can_refund['weixin']>0){
        $can_refund_money = $can_refund['weixin'];
        if($can_refund_money>0) {
            if($remain_refund_money>=$can_refund_money) {
                $remain_refund_money = $remain_refund_money - $can_refund_money;
                $refund['weixin'] = $can_refund_money;
            }else {
                $refund['weixin'] = $remain_refund_money;
                $remain_refund_money = 0;
            }
        }

    }
    if($remain_refund_money>0){
        $return['code'] = false;
        $return['error'] = '数据有误，请联系负责人';
        return $return;
    }
    if(isset($refund['money']) && $refund['money']){
        $MemberWalletLogic = new MemberWalletLogic($order['shop_id'], $order['member_id']);
        $res = $MemberWalletLogic->rebackBalance($refund['money'], 0 , 23); //商城购物使用
        if($res == false){
            $return['code'] = false;
            $return['error'] = $MemberWalletLogic->getError();

        }else{
            $return['refund_money'] = $refund['money'];
        }
    }
    if(isset($refund['platform_money']) && $refund['platform_money']){
        $member = MemberModel::where(['member_id'=>$order['member_id']])->find();
        $money = $member->money;
        $member->money = $member->money+$refund['platform_money'];
        $member->save();
        LogsLogic::money($order['shop_id'], $order['member_id'], 23, 1, $money,$refund['platform_money'], $money+$refund['platform_money'],0,$order['order_id'],0);
        $return['refund_platform_money'] = $refund['platform_money'];
    }
    if(isset($refund['weixin']) && $refund['weixin']){
        $pay_info = $order['pay_info'];
        $pay_info['refund_total_fee'] = $refund['weixin'] * 100;
        $pay_info['out_refund_no'] = $refund_order_sn = createOrderSn($order['order_id'],5);
        $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($order['shop_id']);
        $re= $PaymentGoodsOrderHelper->refundInTheSameWayBf($pay_info);
        if($re['result_code']=='FAIL'){
            $return['code'] = false;
            $return['error'] = $re['err_code_des'];

        }else{
            $return['refund_weixin'] = $refund['weixin'];
        }
    }
    return $return;
}
/*记录日志*/
function checklog($dir,$filename, $data)
{
    $path = "/data/www/uumo-test/runtime/$dir/".date('Ym').'/'.date('Ymd');
    if( !file_exists($path) )
    {
        mkdir($path, 0755, true);
    }

    file_put_contents($path."/".$filename, "[time:".date('Y-m-d H:i:s')."]".$data."\n", FILE_APPEND);
}
function payType($data){
    $type_means=[
        'weixin'=>'微信支付',
        'platform_money'=>'钱包支付',
        'money'=>'储值卡支付',
        'offline' => '线下补单',
    ];
    if(isset($data['mix_pay_type']) && $data['mix_pay_type']){
        $mix_pay_type = explode(',',$data['mix_pay_type']);
        $str = '';
        for($i=0;$i<count($mix_pay_type);$i++){
            $pay_type = $mix_pay_type[$i];
            if($type_means[$pay_type]){
                $str.=$type_means[$pay_type].',';
            }
        }
        $str = trim($str,",");
        return $str ?? '-';
    }else{
        return $type_means[$data['pay_type']] ?? '-';
    }

}
function memberVipTime($order){
    //计算会员有效期时间
    $ls_model = new LevelSettingModel();
    if(null === $level_set = $ls_model->where(['shop_id'=>$order['shop_id'],'is_selected'=>1])->find()){
        $return['code'] = false;
        $return['error'] = '会员设置有误';
        return $return;
    }
    $vip_start_time = $vip_end_time = null;
    $d = date('d');
    $t = date('t');
    $str = '';
    if($d==$t && in_array($d,[28,31])){
        $str = "last day of";
    }
    //等级
    $level = LevelModel::where(['level_id'=>$order['level_id']])->find();
    if($level->time_type == 1){
        $vip_start_time = date("Y-m-d")." 00:00:00";
        $vip_end_time = date("Y-m-d",strtotime($str."+1 year"))." 23:59:59";
    }
    if($level->time_type == 3){
        $vip_start_time = date("Y-m-d")." 00:00:00";
        $vip_end_time = date("Y-m-d",strtotime($str."+1 month"))." 23:59:59";
    }
    if($level->time_type == 4){
        $vip_start_time = date("Y-m-d")." 00:00:00";
        $vip_end_time = date("Y-m-d",strtotime($str."+3 month"))." 23:59:59";
    }
    //修改会员有效时间
    $member_level = MemberLevelModel::where(['shop_id'=>$order['shop_id'],'member_id'=>$order['member_id'],'is_delete'=>0])->find();
    if($member_level){
        $member_level->level_id = $order->level_id;
        $member_level->vip_start_time = $vip_start_time;
        $member_level->vip_end_time = $vip_end_time;
        $member_level->vip_time_type = $level->time_type;
    }else{
        $member_level = new MemberLevelModel();
        $member_level->shop_id = $order['shop_id'];
        $member_level->member_id = $order['member_id'];
        $member_level->level_id = $order->level_id;
        $member_level->vip_start_time = $vip_start_time;
        $member_level->vip_end_time = $vip_end_time;
        $member_level->vip_time_type = $level->time_type;
    }
    $member_level->is_appoint = 0;
    $re = $member_level->save();
    if($re){
        $return['code'] = true;
        $return['error'] = '会员有效期修改成功';
    }else{
        $return['code'] = false;
        $return['error'] = '会员有效期修改错误';
    }

    return $return;
}
//付费会员领券
function memberVipCoupon($order,$level){

    $benefits = LevelBenefitsModel::where(['level_id'=>$level['level_id'],'is_delete'=>0])->find();
    if($benefits){
        $coupon = \app\beautiful\model\CouponModel::where(['coupon_id'=>$benefits['coupon_id'],'status'=>1,'is_delete'=>0])->find();
        $remain_num = $coupon['quota'] - $coupon['take_count'];
        if($coupon && $remain_num>0){
            //是否是股东
            $partner = PartnerModel::where( [

                ['shop_id','=',$order->shop_id],

                ['member_id','=',$order->member_id],

                ['status','=',1],

                ['is_delete','=',0],

            ])->find();

            $num = ($benefits['num']>$remain_num)?$remain_num:$benefits['num'];

            for($i=0;$i<$num;$i++){
                $mc_model = new MemberCouponModel();
                $mc_model->shop_id = $order->shop_id;
                $mc_model->member_id = $order->member_id;
                $mc_model->partner_id = $partner?$partner->partner_id:0;
                $mc_model->type_id = 4;
                $mc_model->coupon_id = $coupon['coupon_id'];
                $mc_model->name = $coupon['name'];
                $mc_model->coupon_money = $coupon['coupon_money'];
                $mc_model->money_limit = $coupon['money_limit'];
                $mc_model->valid_bg_time = $coupon['valid_bg_time'];
                $mc_model->valid_end_time = $coupon['valid_end_time'];
                $mc_model->status = 0;
                $mc_model->save();
            }
            $coupon->take_count = $coupon->take_count + $num;

            $coupon->save();

        }
    }
    return true;
}
//是否有分区打印产品（多个产品都是一个分区打印机那么出一个票）
function goodsProduce($orderId){
    $order = GoodsOrderModel::where(['order_id'=>$orderId])->find();

    $goods_ids = \app\beautiful\model\order\GoodsOrderItemModel::where(['order_id'=>$orderId])->column('goods_id');

    $flash_sale_goods = $pin_tuan_goods = [];

    if($order['order_type']=='flash_sale'){

        $flash_sale = \app\beautiful\model\mall\FlashSaleGoodsModel::whereIn('flash_sale_goods_id',$goods_ids)->select()->toArray();

        foreach ($flash_sale as $k=>$v){

            $flash_sale_goods[$v['goods_id']] = $v['flash_sale_goods_id'];

            $goods_ids[]=$v['goods_id'];
        }

    }
    if($order['order_type']=='pin_tuan'){

        $pin_tuan = \app\beautiful\model\mall\PinTuanGoodsModel::whereIn('pin_tuan_goods_id',$goods_ids)->select()->toArray();

        foreach ($pin_tuan as $k=>$v){

            $pin_tuan_goods[$v['goods_id']] = $v['pin_tuan_goods_id'];

            $goods_ids[]=$v['goods_id'];
        }

    }
    $where['shop_id'] = $order['shop_id'];
    $where['goods_id'] = $goods_ids;//包含有分区打印和无分区打印的产品
    //$where['is_delete'] = 0;
    $return = \app\common\model\ProduceModel::list($where,['a.add_time'=>'desc'],1,999,$flash_sale_goods,$pin_tuan_goods);

    return $return;

}
//是否有分区打印产品（多个产品都是一个分区打印机那么出一个票）
function goodsProduceOld($orderId){
    $order = GoodsOrderModel::where(['order_id'=>$orderId])->find();

    $goods_ids = \app\beautiful\model\order\GoodsOrderItemModel::where(['order_id'=>$orderId])->column('goods_id');

    if($order['order_type']=='flash_sale'){
        $flash_sale_goods = [];

        $flash_sale = \app\beautiful\model\mall\FlashSaleGoodsModel::whereIn('flash_sale_goods_id',$goods_ids)->select()->toArray();

        foreach ($flash_sale as $k=>$v){

            $flash_sale_goods[$v['goods_id']] = $v['flash_sale_goods_id'];

            $goods_ids[]=$v['goods_id'];
        }

    }
    if($order['order_type']=='pin_tuan'){
        $pin_tuan_goods = [];

        $pin_tuan = \app\beautiful\model\mall\PinTuanGoodsModel::whereIn('pin_tuan_goods_id',$goods_ids)->select()->toArray();

        foreach ($pin_tuan as $k=>$v){

            $pin_tuan_goods[$v['goods_id']] = $v['pin_tuan_goods_id'];

            $goods_ids[]=$v['goods_id'];
        }

    }
    $where['shop_id'] = $order['shop_id'];
    $where['goods_id'] = $goods_ids;//包含有分区打印和无分区打印的产品
    $return = \app\common\model\ProduceModel::list($where,['a.add_time'=>'desc'],1,999);

    //子订单表goods_id存的秒杀id,需要单独做处理


    $list = $return['list'];

    if($order['order_type']=='flash_sale'){

        foreach ($list as $k=>$v){

            if(isset($flash_sale_goods[$v['goods_id']])) $list[$k]['other_goods_id'] = $flash_sale_goods[$v['goods_id']];
        }
    }
    if($order['order_type']=='pin_tuan'){

        foreach ($list as $k=>$v){

            if(isset($pin_tuan_goods[$v['goods_id']])) $list[$k]['other_goods_id'] = $pin_tuan_goods[$v['goods_id']];
        }
    }
    $return['list']= $list;
    return $return;

}

/**
 * @param $data['uid']  websocket连接信息
 * @return bool|int
 */
function sendWebsocket($data){
    if(empty($data['uid'])){
        return false;
    }
    $client = stream_socket_client('tcp://127.0.0.1:9002', $errno, $errmsg, 1);
    $res=fwrite($client, json_encode($data)."\n");
    return $res;
}

function pushWebsocket($shop_id,$accont_id,$data){
    $uids = ShopAccountModel::where(['shop_id'=>$shop_id])
        ->where('role_id','=',3)
        ->where('uid','<>','')
        ->where('account_id','<>',$accont_id)
        ->column('uid');
    for ($i=0;$i<count($uids);$i++){
        $data['uid'] = $uids[$i];
        sendWebsocket($data);
    }
    return true;

}
function add_record($buy_order_id=0,$order_id=0,$data){
    $record = new \app\beautiful\model\order\OrderRecordModel();
    $record->shop_id = $data['shop_id'];
    $record->buy_order_id = $buy_order_id;
    $record->order_id = $order_id;
    $record->order_refund_id = $data['order_refund_id'];
    $record->status = $data['status'];
    $record->operate_id = $data['operate_id'];
    if(isset($data['order_item_id'])) $record->order_item_id = $data['order_item_id'];
    if(isset($data['num'])) $record->num = $data['num'];
    $re = $record->save();

    return $re;

}
function getcsvdata($filepath){
    //读取文件
    $objReader = IOFactory::load($filepath);
    //获取其中的数据
    $excelData = $objReader->getActiveSheet()->toArray('', true, true, true, true);
    return $excelData;
}